package com.javazyw.busidao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

public abstract class BatchBaseDAOImpl extends SqlSessionDaoSupport implements BatchBaseDAO {

	private static Map<String, SqlSessionTemplate> sessionTemplateMap;
	
	private static Map<String, BatchBaseDAOImpl> instances = new HashMap<String, BatchBaseDAOImpl>();
	
	private static final String DEFAULT = "default";
	
	private static Log logger = LogFactory.getLog(BatchBaseDAOImpl.class);
	
	
public static BatchBaseDAOImpl getInstance(String dbStr) {
		
		if(dbStr == null || "".equals(dbStr) || "null".equals(dbStr))
			dbStr = DEFAULT;
		
		if (!instances.containsKey(dbStr)) {
			SqlSessionTemplate sqlSessionTemplate = sessionTemplateMap.get(dbStr);
			if (sqlSessionTemplate == null) {
				throw new RuntimeException("dbStr=" + dbStr + ",未找到对应的sqlSessionTemplate");
			}
			BatchBaseDAOImpl dao = new BatchBaseDAOImpl(){
				@Override
				public void operate(SqlSession sq, String statement,
						Object parameter) {
				}
			};
			dao.setSqlSessionTemplate(sqlSessionTemplate);
			
			instances.put(dbStr, dao);
			
			return dao;
		}
		logger.debug("BatchBaseDAOImpl  instances.get("+dbStr+")");
		return  instances.get(dbStr);
	}
	
	public void batchExecute(List<? extends Object> parameterList, String statement, int submitCount) {
		
		batchExecute(parameterList, statement, submitCount, DEFAULT);
	}
	
	public void batchExecute(List<? extends Object> parameterList, String statement, int submitCount, String dbStr) {
		
		SqlSession sq = getInstance(dbStr).getSqlSession();
		int batch = 0;
		for (Object o : parameterList) {
			batch++;
			
			operate(sq, statement, o);
			if (batch == submitCount) {
				sq.flushStatements();
				batch = 0;
			}
		}
		sq.flushStatements();
		
	}
	
	
	public abstract void operate(SqlSession sq, String statement, Object parameter);

	public static Map<String, SqlSessionTemplate> getSessionTemplateMap() {
		return sessionTemplateMap;
	}

	public static void setSessionTemplateMap(
			Map<String, SqlSessionTemplate> sessionTemplateMap) {
		BatchBaseDAOImpl.sessionTemplateMap = sessionTemplateMap;
	}
	
	
}
